
//create by wang zhong, 2012-08-02 09:28:59


#ifndef _FILEOPS_H_
#define _FILEOPS_H_

#include "OSHeaders.h"
#include <sys/types.h>
#include <sys/stat.h>
#ifndef __Win32__
#include <unistd.h>
#endif

class FileOps
{
public:
    static Bool16 DirExist(const char* pfilepath);
    static Bool16 Exists(const char* pfilepath);
    static UInt64 GetLength(const char* pfilepath)
    {
        struct stat statbuf;
        Stat(pfilepath, statbuf);
        return (UInt64 )statbuf.st_size;
    }
    static SInt64 LastModificationTime(const char* pfilepath) //milliseconds
    {
        struct stat statbuf;
        if(!Stat(pfilepath, statbuf))return -1;
        return LastModificationTime(statbuf);
    }
    static SInt64 LastAccessTime(const char* pfilepath)//milliseconds
    {
        struct stat statbuf;
        if(!Stat(pfilepath, statbuf))return -1;
        return LastAccessTime(statbuf);
    }
    static SInt64 LastStatusChangeTime(const char* pfilepath) //milliseconds
    {
        struct stat statbuf;
        if(!Stat(pfilepath, statbuf))return -1;
        return LastStatusChangeTime(statbuf);
    }

    static Bool16 Stat(const char* pfilepath, struct stat &statBuf);
    static SInt64 LastAccessTime(struct stat &statBuf) //milliseconds
    {
        return (SInt64)statBuf.st_atime * 1000;
    }
    static SInt64 LastModificationTime(struct stat &statBuf) //milliseconds
    {
        return (SInt64)statBuf.st_mtime * 1000;
    }
    static SInt64 LastStatusChangeTime(struct stat &statBuf) //milliseconds
    {
        return (SInt64)statBuf.st_ctime * 1000;
    }

    //Both these functions return QTSS_NoErr, QTSS_FileExists, or POSIX errorcode
    //Makes whatever directories in this path that don't exist yet 
    static OS_Error RecursiveMakeDir(char *inPath);
    //Makes the directory at the end of this path
    static OS_Error MakeDir(char *inPath);


public:
    FileOps();
    FileOps(const char* pfilepath, Bool16 readOnly);
    ~FileOps(){Close();}
    void Set(const char* pfilepath, Bool16 readOnly);
	void Set(const char* pfilepath, Bool16 readOnly, Bool16 truncated);
	void Open(const char* pfilepath, Bool16 readOnly);
    void Close();
    
    int  GetFD(){ return m_nFileFd; }
    Bool16 IsDir(){ return m_bIsDir; }
    Bool16 IsOpened(){ return m_nFileFd != -1;}
    SInt64 GetModTime()                { return m_s64ModTime; }
    UInt64 GetLength()                 { return m_u64Length; }
    OS_Error Read(UInt64 inPosition, void* inBuffer, SInt32 inLength, SInt32& outRcvLen);
    OS_Error Write(UInt64 inPosition, void* inBuffer, SInt32 inLength, SInt32& outRcvLen);
    const char* GetFilepath(){return m_strFilepath; }
	OS_Error DelFile(const char *fileName);

protected:
private:
    char    m_strFilepath[512];
    int     m_nFileFd;
    UInt64  m_u64Length;
    SInt64  m_s64ModTime;
    Bool16  m_bIsDir;
    Bool16  m_bReadOnly;

};
#endif
